package com.example.autulin.gb28181_android;

import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.autulin.gb28181library.JNIBridge;
import com.autulin.gb28181library.MediaRecorderBase;
import com.autulin.gb28181library.MediaRecorderNative;
import com.autulin.gb28181library.utils.DeviceUtils;
import com.autulin.gb28181library.utils.JNIBridgeInterface;
import com.example.autulin.gb28181_android.utils.NetUtils;
import com.example.autulin.gb28181_android.utils.PermissionManager;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class DemoActivity extends AppCompatActivity implements MediaRecorderBase.OnErrorListener, MediaRecorderBase.OnPreparedListener, View.OnClickListener, JNIBridgeInterface {

    private Button start_btn;
    private SurfaceView mSurfaceView;
    private MediaRecorderNative mMediaRecorder;
    private Button register_btn;
    private EditText server_ip;
    private EditText server_port;
    private EditText server_id;
    private EditText user_id;
    private EditText user_password;
    private TextView local_ip;

    private final static String TAG = "DemoActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 防止锁屏
        setContentView(R.layout.activity_demo);
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        initData();
        initView();
        initPermission();
        try {
            Log.e("log", "path: " + MediaRecorderBase.getLogOutPutPath());
            Runtime.getRuntime().exec("logcat -f " + MediaRecorderBase.getLogOutPutPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        JNIBridge.jNIBridgeInterface = this;
    }

    @Override
    public void onResume() {
        super.onResume();
        //初始化
        if (mMediaRecorder == null) {
            initMediaRecorder();
        } else {
            mMediaRecorder.prepare();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        mMediaRecorder.release();
    }

    //初始化视频参数用的
    private void initData() {
        MediaRecorderBase.QUEUE_MAX_SIZE = 20;
        Log.i("debug", "SMALL_VIDEO_HEIGHT: " + MediaRecorderBase.SMALL_VIDEO_HEIGHT + ", SMALL_VIDEO_WIDTH:" + MediaRecorderBase.SMALL_VIDEO_WIDTH);
    }

    private void initView() {
        start_btn = findViewById(R.id.start_btn);
        start_btn.setOnClickListener(this);
        mSurfaceView = findViewById(R.id.record_preview);
        register_btn = findViewById(R.id.register_btn);
        register_btn.setOnClickListener(this);
        local_ip = findViewById(R.id.local_ip);
        local_ip.setText(NetUtils.getIPAddress(DemoActivity.this));
        server_ip = findViewById(R.id.server_ip);
        server_port = findViewById(R.id.server_port);
        server_id = findViewById(R.id.server_id);
        user_id = findViewById(R.id.user_id);
        user_password = findViewById(R.id.user_password);
        //server_ip.setText("192.168.31.78");
        server_ip.setText("10.39.62.3");
        //server_ip.setText("10.2.112.65");
        server_ip.setText("123.58.243.65");
        server_port.setText("5060");
        server_id.setText("34020000002000000001");
        user_id.setText("34020000001320000010");
        user_password.setText("123456");
    }

    /**
     * 初始化权限事件
     */
    private void initPermission() {
        //检查权限
        PermissionManager.requestPermission(DemoActivity.this, new PermissionManager.Callback() {
            @Override
            public void permissionSuccess() {
                PermissionManager.requestPermission(DemoActivity.this, new PermissionManager.Callback() {
                    @Override
                    public void permissionSuccess() {
                        PermissionManager.requestPermission(DemoActivity.this, new PermissionManager.Callback() {
                            @Override
                            public void permissionSuccess() {
                                Toast.makeText(DemoActivity.this, "授权成功！", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void permissionFailed() {
                                Toast.makeText(DemoActivity.this, "授权失败！", Toast.LENGTH_SHORT).show();
                            }
                        }, Permission.Group.STORAGE);
                    }

                    @Override
                    public void permissionFailed() {
                        Toast.makeText(DemoActivity.this, "请求权限失败！", Toast.LENGTH_SHORT).show();
                    }
                }, Permission.Group.MICROPHONE);
            }

            @Override
            public void permissionFailed() {

            }
        }, Permission.Group.CAMERA);

    }

    /**
     * 初始化拍摄SDK
     */
    private void initMediaRecorder() {
        mMediaRecorder = new MediaRecorderNative();
        mMediaRecorder.setOnErrorListener(this);
        mMediaRecorder.setOnPreparedListener(this);
        mMediaRecorder.setCameraFront();   // 设置前置摄像头
        // 设置输出
        // mMediaRecorder.setFileOutPut("aaa.ps");  //输出到文件，这里demo是/sdcard/pstest/tttttt.ps
        //mMediaRecorder.setUdpOutPut(ip, port, 1);
        mMediaRecorder.setSurfaceHolder(mSurfaceView.getHolder());
        mMediaRecorder.prepare();
    }

    /**
     * 初始化画布
     */
    private void initSurfaceView() {
        final int w = DeviceUtils.getScreenWidth(this);
        // 避免摄像头的转换，只取上面h部分
        // ((RelativeLayout.LayoutParams) bottomLayout.getLayoutParams()).topMargin = (int) (w / (MediaRecorderBase.SMALL_VIDEO_HEIGHT / (MediaRecorderBase.SMALL_VIDEO_WIDTH * 1.0f)));
        int width = w;
        int height = (int) (w * (MediaRecorderBase.mSupportedPreviewWidth * 1.0f)) / MediaRecorderBase.SMALL_VIDEO_HEIGHT;
        Log.e("debug", "initSurfaceView: w=" + width + ",h=" + height);
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mSurfaceView.getLayoutParams();
        lp.width = width;
        lp.height = height;
        mSurfaceView.setLayoutParams(lp);
    }

    /**
     * 摄像头初始化完毕，初始化显示
     */
    @Override
    public void onPrepared() {
        initSurfaceView();
    }

    @Override
    public void onVideoError(int what, int extra) {
    }

    @Override
    public void onAudioError(int what, String message) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_btn:
                if (mMediaRecorder != null) {
                    if (!mMediaRecorder.mRecording) {
                        mMediaRecorder.setUdpOutPut("127.0.0.1", 15060, 1);
                        start_btn.setText("点击结束");
                        mMediaRecorder.startMux();
                    } else {
                        start_btn.setText("点击开始");

                        mMediaRecorder.endMux();
                    }
                }
                break;

            case R.id.register_btn:
                register_btn.setEnabled(false);
                String serverIp = server_ip.getText().toString();
                String serverPort = server_port.getText().toString();
                String serverId = server_id.getText().toString();
                String userId = user_id.getText().toString();
                String userPassword = user_password.getText().toString();
                String localIp = local_ip.getText().toString();
                //注册服务
                JNIBridge.RegisterFromJNI(serverIp, serverPort, serverId, userId, userPassword, localIp);
                break;
        }


    }

    @Override
    public void jniCallBack(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(message);
                    String control_type = jsonObject.getString("control_type");
                    if ("Play".equals(control_type)) {

                        String media_ip = jsonObject.getString("media_ip");
                        Integer media_port = jsonObject.getInt("media_port");
                        Log.i(TAG, "实时点播,ip=" + media_ip + ",port=" + media_port);
                        mMediaRecorder.setUdpOutPut(media_ip, media_port, 99);
                        if (mMediaRecorder != null) {
                            if (!mMediaRecorder.mRecording) {
                                start_btn.setText("点击结束");
                                mMediaRecorder.endMux();
                                mMediaRecorder.startMux();
                            } else {
                                start_btn.setText("点击开始");
                                mMediaRecorder.endMux();
                                mMediaRecorder.startMux();
                            }
                        }

                    } else if ("message".equals(control_type)) {

                        String message = jsonObject.getString("message");
                        runOnUiThread(()->{
                            register_btn.setEnabled(true);
                            Toast.makeText(DemoActivity.this, message, Toast.LENGTH_LONG).show();

                        });


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }
}
